package com.woniu.idearbac.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutFilter;

import javax.annotation.Resource;

/**
 * @author ：fengSir
 * @date ：Created By 2022-12-01 15:32
 * @description ：TODO
 */
@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled=true,securedEnabled=true,jsr250Enabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    private UserDetailsService userDetailsService;
    @Resource
    private JWTLogoutSuccessHandler jwtLogoutSuccessHandler;
    @Resource
    private MyAccessDeniedHandler accessDeniedHandler;

    /**
     * 解决 无法直接注入 AuthenticationManager
     * 非必填项，如果没有提示找不到则无需配置，配置上之后反而会报错
     */
    //@Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
    @Bean
    public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter(){
        return new JwtAuthenticationTokenFilter();
    }
    @Bean
    SuccessSecurity loginAuthenticationSuccessHandler(){
        return new SuccessSecurity();
    }
    @Bean
    LoseSecurity loginAuthenticationFailureHandler(){
        return new LoseSecurity();
    }
    @Bean
    LoginFilter loginFilter() throws Exception {
        LoginFilter loginFilter = new LoginFilter();
        loginFilter.setAuthenticationManager(authenticationManager());
        //登录失败的处理
        loginFilter.setAuthenticationFailureHandler(loginAuthenticationFailureHandler());
        //登录成功处理器
        loginFilter.setAuthenticationSuccessHandler(loginAuthenticationSuccessHandler());
        return loginFilter;
    }
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        // CRSF禁用，不使用session
        httpSecurity.csrf().disable();
        //允许跨域
        httpSecurity.cors();
        // 基于token，所以不需要session
        httpSecurity.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        //放行user/login
        httpSecurity.authorizeRequests()
                .antMatchers("/users/login")
                .permitAll()
               // .antMatchers("/users/del/**").hasAuthority("user:delete")
                .anyRequest()
                .authenticated();
        httpSecurity.addFilterAt(loginFilter(), UsernamePasswordAuthenticationFilter.class);
        // 添加JWTfilter,让其在UsernamePasswordAuthenticationFilter过滤器之前执行
        //退出成功
        httpSecurity.logout().logoutSuccessHandler(jwtLogoutSuccessHandler);
        // 修改jwtAuthenticationTokenFilter在` LogoutFilter`之前执行，不然会出现空指针
        httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter(),LogoutFilter.class);
        //配置异常处理
        httpSecurity.exceptionHandling().accessDeniedHandler(accessDeniedHandler);

    }
    /**
     * 强散列哈希加密实现
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 身份认证接口
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }
}
